import React, { useState, useEffect, useCallback, useMemo } from "react";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
  CardDescription,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Slider } from "@/components/ui/slider";
import { Badge } from "@/components/ui/badge";
import { useToast } from "@/components/ui/use-toast";
import { Alert, AlertDescription } from "@/components/ui/alert";
import {
  Save,
  Calculator,
  AlertTriangle,
  Info,
  GitCommitHorizontal,
  Loader2,
  Zap,
} from "lucide-react";
import {
  Tooltip,
  TooltipProvider,
  TooltipTrigger,
  TooltipContent,
} from "@/components/ui/tooltip";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { ConductorSpecAPI } from "@/api/ConductorSpec";
import FormulaDisplay from "../FormulaDisplay";

const getConductorCategory = (conductorSpec) => {
  if (!conductorSpec || !conductorSpec.type) return "unknown";
  const typeUpper = conductorSpec.type.toUpperCase();
  if (typeUpper.includes("AAAC") || typeUpper.includes("ACSS")) return "alloy";
  if (typeUpper.includes("ACSR") || typeUpper.includes("LGJ"))
    return "standard";
  return "unknown";
};

const COEFFICIENTRANGES = {
  traction: {
    standard: { min: 0.2, max: 0.3, step: 0.01, label: "钢芯铝绞线 (0.2-0.3)" },
    alloy: {
      min: 0.14,
      max: 0.2,
      step: 0.01,
      label: "钢芯铝合金绞线 (0.14-0.2)",
    },
  },
  tension: {
    standard: {
      min: 0.12,
      max: 0.18,
      step: 0.01,
      label: "钢芯铝绞线 (0.12-0.18)",
    },
    alloy: {
      min: 0.09,
      max: 0.125,
      step: 0.005,
      label: "钢芯铝合金绞线 (0.09-0.125)",
    },
  },
  tractionRope: {
    standardWire: { value: 0.6, label: "适用钢芯铝绞线 (0.6)" },
    alloyWire: { value: 0.4, label: "适用钢芯铝合金绞线 (0.4)" },
  },
  guideRope: {
    steel: { value: 0.25, label: "钢丝绳 (1/4)" },
    fiber: { value: 0.167, label: "纤维绳 (1/6)" },
  },
};

export default function TractionCalculator({
  scheme,
  onUpdate,
  crossingPoint,
}) {
  const { toast } = useToast();
  const [conductorSpec, setConductorSpec] = useState(null);
  const [isLoadingSpec, setIsLoadingSpec] = useState(true);
  console.log(scheme, "schemescheme");
  console.log(crossingPoint, "crossingPointcrossingPoints");

  const [params, setParams] = useState(() => ({
    tensionStringingInput: {
      simultaneousReleaseCount:
        scheme.tensionStringingInput?.simultaneousReleaseCount || 1, //同时牵放根数
      tractorCoefficient:
        scheme.tensionStringingInput?.tractorCoefficient ?? 0.2, //牵引机系数
      tensionerCoefficient:
        scheme.tensionStringingInput?.tensionerCoefficient ?? 0.12, //张力机系数
      tractionRopeType:
        scheme.tensionStringingInput?.tractionRopeType || "standardWire", //牵引绳类型
      guideRopeType: scheme.tensionStringingInput?.guideRopeType || "steel", //导引绳类型
      conductorTypeOverride:
        scheme.tensionStringingInput?.conductorTypeOverride, //导线类型
    },
  }));

  // 导线分类：基于 override 或 spec
  const conductorCategory = useMemo(() => {
    if (params.tensionStringingInput.conductorTypeOverride)
      return params.tensionStringingInput.conductorTypeOverride;
    return getConductorCategory(conductorSpec);
  }, [conductorSpec, params.tensionStringingInput.conductorTypeOverride]);

  // 初始化系数到嵌套对象
  useEffect(() => {
    if (conductorCategory !== "unknown") {
      setParams((prev) => {
        const tractionRange = COEFFICIENTRANGES.traction[conductorCategory];
        const tensionRange = COEFFICIENTRANGES.tension[conductorCategory];
        return {
          ...prev,
          tensionStringingInput: {
            ...prev.tensionStringingInput,
            tractorCoefficient:
              prev.tensionStringingInput.tractorCoefficient ??
              tractionRange.min,
            tensionerCoefficient:
              prev.tensionStringingInput.tensionerCoefficient ??
              tensionRange.min,
          },
        };
      });
    }
  }, [conductorCategory]);
  // const conductorType =

  useEffect(() => {
    console.log(222222);

    const loadSpec = async () => {
      if (scheme.insulband?.parametersWire?.conductorType) {
        setIsLoadingSpec(true);
        try {
          const specsRes = await ConductorSpecAPI.getList();
          const specsList = specsRes.data;
          const matchedSpec = specsList.find(
            (spec) =>
              spec &&
              spec.model === scheme.insulband?.parametersWire?.conductorType
          );
          if (specsList && specsList.length > 0) setConductorSpec(matchedSpec);
          else {
            setConductorSpec(null);
            toast({ variant: "warning", title: "导线规格未找到" });
          }
        } catch (error) {
          console.error("加载导线规格失败:", error);
          toast({ variant: "destructive", title: "加载导线规格失败" });
        } finally {
          setIsLoadingSpec(false);
        }
      } else {
        setIsLoadingSpec(false);
        setConductorSpec(null);
      }
    };
    loadSpec();
  }, [scheme.insulband?.parametersWire?.conductorType, toast]);

  const handleParamChange = (key, value) => {
    setParams((prev) => ({
      ...prev,
      tensionStringingInput: {
        ...prev.tensionStringingInput,
        [key]: value,
      },
    }));
  };

  const handleSliderChange = (key, value) => {
    setParams((prev) => ({
      ...prev,
      tensionStringingInput: {
        ...prev.tensionStringingInput,
        [key]: value[0],
      },
    }));
  };

  const calculationResults = useMemo(() => {
    if (!conductorSpec?.breakingForceKn)
      return { error: "缺少导线额定拉断力。" };
    if (conductorCategory === "unknown")
      return { error: "请手动选择导线类型。" };

    const {
      simultaneousReleaseCount,
      tractorCoefficient,
      tensionerCoefficient,
      tractionRopeType,
      guideRopeType,
    } = params.tensionStringingInput;
    const breakingForce = conductorSpec.breakingForceKn;

    if (
      !simultaneousReleaseCount ||
      !tractorCoefficient ||
      !tensionerCoefficient
    )
      return { error: "请输入所有计算参数。" };

    const requiredTractionForce =
      simultaneousReleaseCount * tractorCoefficient * breakingForce;
    const requiredBrakingTension = breakingForce * tensionerCoefficient;
    const tractionRopeCoeff =
      COEFFICIENTRANGES.tractionRope[tractionRopeType].value;
    const requiredTractionRopeBreakingForce =
      simultaneousReleaseCount * tractionRopeCoeff * breakingForce;
    const guideRopeCoeff = COEFFICIENTRANGES.guideRope[guideRopeType].value;
    const requiredGuideRopeBreakingForce =
      requiredTractionRopeBreakingForce * guideRopeCoeff;

    return {
      requiredTractionForce: requiredTractionForce.toFixed(2),
      requiredBrakingTension: requiredBrakingTension.toFixed(2),
      requiredTractionRopeBreakingForce:
        requiredTractionRopeBreakingForce.toFixed(2),
      requiredGuideRopeBreakingForce: requiredGuideRopeBreakingForce.toFixed(2),
      tractionRopeCoeff,
      guideRopeCoeff,
      error: null,
    };
  }, [params.tensionStringingInput, conductorSpec, conductorCategory]);

  const handleSave = () => {
    if (calculationResults.error) {
      toast({
        variant: "destructive",
        title: "保存失败",
        description: calculationResults.error,
      });
      return;
    }
    onUpdate({
      tensionStringingInput: params.tensionStringingInput,
      tensionStringingResult: {
        guideRopeMinBreakingForce: parseFloat(
          calculationResults.requiredGuideRopeBreakingForce //导引绳最小破断力
        ),
        minTractionForce: parseFloat(
          calculationResults.requiredTractionForce //最小牵引力
        ),
        minBrakingTension: parseFloat(
          calculationResults.requiredBrakingTension //最小制动张力
        ),
        tractionRopeMinBreakingForce: parseFloat(
          calculationResults.requiredTractionRopeBreakingForce //牵引绳最小破断力
        ),
      },
    });
    toast({ title: "保存成功", description: "牵引计算参数和结果已保存。" });
  };

  if (isLoadingSpec)
    return (
      <div className="flex justify-center p-8">
        <Loader2 className="w-8 h-8 animate-spin" />
      </div>
    );
  if (!scheme.insulband?.parametersWire?.conductorType)
    return (
      <Alert variant="destructive">
        <AlertTriangle className="h-4 w-4" />
        <AlertDescription>方案中未设置导线型号。</AlertDescription>
      </Alert>
    );
  if (!conductorSpec)
    return (
      <Alert variant="destructive">
        <AlertTriangle className="h-4 w-4" />
        <AlertDescription>
          未找到导线 "{scheme.insulband?.parametersWire?.conductorType}"
          的规格信息。
        </AlertDescription>
      </Alert>
    );

  const tractionRange =
    conductorCategory !== "unknown"
      ? COEFFICIENTRANGES.traction[conductorCategory]
      : null;
  const tensionRange =
    conductorCategory !== "unknown"
      ? COEFFICIENTRANGES.tension[conductorCategory]
      : null;

  const formulas = [
    {
      name: "单根导线牵引张力估算",
      description: "根据导线破断力估算单根导线的牵引张力",
      formula: "TSingle ≈ 0.25 × TBreaking",
      variables: [
        { symbol: "TSingle", description: "单根导线牵引张力", unit: "kN" },
        { symbol: "TBreaking", description: "导线额定破断力", unit: "kN" },
      ],
      conditions: [
        "假设牵引张力为破断力的25%",
        "实际值需根据档距、高差、摩擦系数等计算",
        "此为简化估算，仅用于设备选型参考",
      ],
    },
    {
      name: "牵引机所需牵引力",
      description: "考虑同时牵放数量和安全系数的牵引机牵引力",
      formula: "FTraction = TSingle × N × KT",
      variables: [
        {
          symbol: "FTraction",
          description: "牵引机最小额定牵引力",
          unit: "kN",
        },
        { symbol: "TSingle", description: "单根导线牵引张力", unit: "kN" },
        { symbol: "N", description: "同时牵放导线根数", unit: "根" },
        { symbol: "KT", description: "牵引机系数", unit: "-" },
      ],
      conditions: [
        "牵引机系数一般取1.2",
        "需考虑牵引过程中的动态荷载",
        "选择牵引机时应留有余量",
      ],
      reference: "DL/T 5301-2013 第7章 牵引设备",
    },
    {
      name: "张力机所需制动力",
      description: "张力机对导线的制动张力要求",
      formula: "FTension = TSingle × N × KS",
      variables: [
        { symbol: "FTension", description: "张力机最小额定制动力", unit: "kN" },
        { symbol: "TSingle", description: "单根导线牵引张力", unit: "kN" },
        { symbol: "N", description: "同时牵放导线根数", unit: "根" },
        { symbol: "KS", description: "张力机系数", unit: "-" },
      ],
      conditions: [
        "张力机系数一般取1.0",
        "需确保张力机能稳定控制导线张力",
        "防止导线在牵引过程中失控",
      ],
      reference: "DL/T 5301-2013 第7章 张力设备",
    },
    {
      name: "牵引绳所需破断力",
      description: "牵引绳需满足的最小破断力要求",
      formula: "FRope = FTraction × KRope",
      variables: [
        { symbol: "FRope", description: "牵引绳最小综合破断力", unit: "kN" },
        { symbol: "FTraction", description: "牵引机最大牵引力", unit: "kN" },
        { symbol: "KRope", description: "牵引绳安全系数", unit: "-" },
      ],
      conditions: [
        "牵引绳安全系数一般取2.0",
        "需考虑牵引绳的磨损和老化",
        "钢丝绳和合成纤维绳的安全系数要求不同",
      ],
      reference: "DL/T 5301-2013 第8.3节 牵引绳",
    },
    {
      name: "导引绳所需破断力",
      description: "导引绳需满足的最小破断力要求",
      formula: "FGuide ≈ 0.5 × FTraction",
      variables: [
        { symbol: "FGuide", description: "导引绳最小综合破断力", unit: "kN" },
        { symbol: "FTraction", description: "牵引机最大牵引力", unit: "kN" },
      ],
      conditions: [
        "导引绳受力通常小于牵引绳",
        "估算时取牵引力的50%",
        "实际选择时应有适当余量",
      ],
    },
  ];
  return (
    <TooltipProvider>
      <FormulaDisplay
        standard="DL/T 5301-2013 输电线路工程架线施工工艺规程"
        formulas={formulas}
      />
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 mt-6">
        {/* 左侧栏: 输入参数 */}
        <div className="space-y-4">
          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-lg flex items-center gap-2">
                <GitCommitHorizontal className="w-4 h-4 text-blue-600" />
                输入参数
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label className="text-xs">同时牵放根数 (n)</Label>
                  <Input
                    type="number"
                    min="1"
                    step="1"
                    value={
                      params.tensionStringingInput.simultaneousReleaseCount
                    }
                    onChange={(e) => {
                      const inputValue = parseInt(e.target.value);
                      const validValue =
                        isNaN(inputValue) || inputValue < 1 ? 1 : inputValue;
                      handleParamChange("simultaneousReleaseCount", validValue);
                    }}
                    className="mt-1 h-8"
                  />
                </div>
                <div className="p-2 bg-slate-50 rounded border text-center">
                  <p className="text-xs text-gray-500">{conductorSpec.model}</p>
                  <p className="text-sm font-bold">
                    {conductorSpec.breakingForceKn} kN
                  </p>
                </div>
              </div>

              {conductorCategory === "unknown" && (
                <div className="p-3 bg-yellow-50 rounded border border-yellow-200">
                  <Label className="font-semibold text-yellow-800 text-sm">
                    请手动选择导线类型：
                  </Label>
                  <Select
                    value={
                      params.tensionStringingInput.conductorTypeOverride || ""
                    }
                    onValueChange={(value) =>
                      handleParamChange("conductorTypeOverride", value)
                    }
                  >
                    <SelectTrigger className="mt-1 h-8">
                      <SelectValue placeholder="选择导线类型" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="standard">
                        钢芯铝绞线 (ACSR/LGJ)
                      </SelectItem>
                      <SelectItem value="alloy">
                        钢芯铝合金绞线 (AAAC/ACSS)
                      </SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              )}

              {conductorCategory !== "unknown" && (
                <div className="space-y-4">
                  <div>
                    <Label className="text-xs flex items-center gap-1">
                      牵引机系数 (Kq){" "}
                      <Tooltip>
                        <TooltipTrigger asChild>
                          <Info className="w-3 h-3 cursor-help" />
                        </TooltipTrigger>
                        <TooltipContent>{tractionRange.label}</TooltipContent>
                      </Tooltip>
                    </Label>
                    <div className="flex items-center gap-2 mt-1">
                      <Slider
                        value={[
                          params.tensionStringingInput.tractorCoefficient,
                        ]}
                        onValueChange={(v) =>
                          handleSliderChange("tractorCoefficient", v)
                        }
                        min={tractionRange.min}
                        max={tractionRange.max}
                        step={tractionRange.step}
                        className="flex-1"
                      />
                      <Input
                        type="number"
                        value={params.tensionStringingInput.tractorCoefficient}
                        onChange={(e) => {
                          const inputValue = parseFloat(e.target.value);
                          const validValue = isNaN(inputValue)
                            ? tractionRange.min
                            : Math.max(
                                tractionRange.min,
                                Math.min(tractionRange.max, inputValue)
                              );
                          handleParamChange("tractorCoefficient", validValue);
                        }}
                        className="w-20 h-8 text-center"
                      />
                    </div>
                  </div>
                  <div>
                    <Label className="text-xs flex items-center gap-1">
                      张力机系数 (Kz){" "}
                      <Tooltip>
                        <TooltipTrigger asChild>
                          <Info className="w-3 h-3 cursor-help" />
                        </TooltipTrigger>
                        <TooltipContent>{tensionRange.label}</TooltipContent>
                      </Tooltip>
                    </Label>
                    <div className="flex items-center gap-2 mt-1">
                      <Slider
                        value={[
                          params.tensionStringingInput.tensionerCoefficient,
                        ]}
                        onValueChange={(v) =>
                          handleSliderChange("tensionerCoefficient", v)
                        }
                        min={tensionRange.min}
                        max={tensionRange.max}
                        step={tensionRange.step}
                        className="flex-1"
                      />
                      <Input
                        type="number"
                        value={
                          params.tensionStringingInput.tensionerCoefficient
                        }
                        onChange={(e) => {
                          const inputValue = parseFloat(e.target.value);
                          const validValue = isNaN(inputValue)
                            ? tensionRange.min
                            : Math.max(
                                tensionRange.min,
                                Math.min(tensionRange.max, inputValue)
                              );
                          handleParamChange("tensionerCoefficient", validValue);
                        }}
                        className="w-20 h-8 text-center"
                      />
                    </div>
                  </div>
                  <div>
                    <Label className="text-xs">牵引绳类型</Label>
                    <Select
                      value={params.tensionStringingInput.tractionRopeType}
                      onValueChange={(value) =>
                        handleParamChange("tractionRopeType", value)
                      }
                    >
                      <SelectTrigger className="h-8 mt-1">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="standardWire">
                          适用钢芯铝绞线 (系数 0.6)
                        </SelectItem>
                        <SelectItem value="alloyWire">
                          适用钢芯铝合金绞线 (系数 0.4)
                        </SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                  <div>
                    <Label className="text-xs">导引绳类型</Label>
                    <Select
                      value={params.tensionStringingInput.guideRopeType}
                      onValueChange={(value) =>
                        handleParamChange("guideRopeType", value)
                      }
                    >
                      <SelectTrigger className="h-8 mt-1">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="steel">钢丝绳 (系数 1/4)</SelectItem>
                        <SelectItem value="fiber">纤维绳 (系数 1/6)</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>
              )}
            </CardContent>
          </Card>
        </div>

        {/* 右侧栏: 计算结果 */}
        <div className="space-y-4">
          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-lg flex items-center gap-2">
                <Calculator className="w-4 h-4 text-purple-600" />
                计算结果
              </CardTitle>
            </CardHeader>
            <CardContent>
              {calculationResults.error ? (
                <Alert variant="destructive">
                  <AlertTriangle className="h-4 w-4" />
                  <AlertDescription>
                    {calculationResults.error}
                  </AlertDescription>
                </Alert>
              ) : (
                <div className="space-y-4">
                  <div>
                    <h3 className="text-sm font-semibold mb-2 flex items-center gap-2">
                      <Zap className="w-4 h-4 text-indigo-600" />
                      设备选型
                    </h3>
                    <div className="grid grid-cols-2 gap-3">
                      <div className="p-3 bg-blue-50 rounded border text-center">
                        <h4 className="text-xs font-medium text-blue-700">
                          最小牵引力 (Fq)
                        </h4>
                        <p className="text-xl font-bold text-blue-900">
                          {calculationResults.requiredTractionForce} kN
                        </p>
                      </div>
                      <div className="p-3 bg-green-50 rounded border text-center">
                        <h4 className="text-xs font-medium text-green-700">
                          最小制动张力 (Fz)
                        </h4>
                        <p className="text-xl font-bold text-green-900">
                          {calculationResults.requiredBrakingTension} kN
                        </p>
                      </div>
                    </div>
                  </div>
                  <div>
                    <h3 className="text-sm font-semibold mb-2 flex items-center gap-2">
                      <GitCommitHorizontal className="w-4 h-4 text-orange-600" />
                      绳索选型
                    </h3>
                    <div className="grid grid-cols-2 gap-3">
                      <div className="p-3 bg-orange-50 rounded border text-center">
                        <h4 className="text-xs font-medium text-orange-700">
                          牵引绳最小破断力
                        </h4>
                        <p className="text-xl font-bold text-orange-900">
                          {calculationResults.requiredTractionRopeBreakingForce}{" "}
                          kN
                        </p>
                      </div>
                      <div className="p-3 bg-purple-50 rounded border text-center">
                        <h4 className="text-xs font-medium text-purple-700">
                          导引绳最小破断力
                        </h4>
                        <p className="text-xl font-bold text-purple-900">
                          {calculationResults.requiredGuideRopeBreakingForce} kN
                        </p>
                      </div>
                    </div>
                  </div>
                </div>
              )}
            </CardContent>
          </Card>
          <div className="flex justify-end">
            <Button
              onClick={handleSave}
              disabled={!!calculationResults.error}
              className="w-full lg:w-auto"
            >
              <Save className="w-4 h-4 mr-2" />
              保存计算结果
            </Button>
          </div>
        </div>
      </div>
    </TooltipProvider>
  );
}
